<?php

namespace app\store\controller;

use app\admin\common\Base;
use think\Db;

use app\store\model\Check as Model;
use app\store\model\CheckDetails as ModelDetails;

//盘点
class Pandian extends Base
{
    public function index()
    {

        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if ($map == '') {
                $list = Db::name('check')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('check')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('check')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('check')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }
            foreach ($list as $key => $value) {
                $list[$key]['addtime'] = date('Y-m-d', $value['addtime']);
                $list[$key]['store_name'] = $value['store_id'] == 0 ? '所有仓库' : Db::name('store')->where('id', $value['store_id'])->value('name');
                $list[$key]['result_arr'] = explode(',', $value['result']);
                foreach ($list[$key]['result_arr'] as $k => $v) {
                    $list[$key]['result_arr'][$k] = substr($v, strripos($v, ' ') + 1);
                }
                foreach ($list[$key]['result_arr'] as $k => $v) {
                    $list[$key]['result_id'][$k] = Db::name('stock_record')->where('sn', $v)->value('id');
                    $list[$key]['pandianky'][$k] = strpos($v, 'QTCK') !== false ? 0 : 1;
                }
            }
            // halt($list);
            return $this->grid_data($list, $count, $page, $limit);
        }

        return $this->fetch();
    }

    public function add()
    {

        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if ($map == '') {
                $list = Db::name('store')->where('status', 0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('store')->where('status', 0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('store')->where('status', 0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('store')->where('status', 0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }
            $arr = [];
            foreach ($list as $key => $value) {
                $goods = Db::name('goods')->where('status', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
                foreach ($goods as $k => $v) {
                    $instock = Db::name('stock_record_good')->alias('a')->join('stock_record b', 'a.pid = b.id')->where(['a.store_id' => $value['id'], 'a.good_id' => $v['id']])->where(['a.is_del' => 0, 'a.enterprise_id' => $this->EnterpriseId])->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId, 'b.status' => 1])->where('a.o_type', 0)->sum('number');
                    $outstock = Db::name('stock_record_good')->alias('a')->join('stock_record b', 'a.pid = b.id')->where(['a.store_id' => $value['id'], 'a.good_id' => $v['id']])->where(['a.is_del' => 0, 'a.enterprise_id' => $this->EnterpriseId])->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId, 'b.status' => 1])->where('a.o_type', 1)->sum('number');
                    $arr[$k]['store_id'] = $value['id'];
                    $arr[$k]['store_name'] = $value['name'];
                    $arr[$k]['goods_name'] = $v['name'];
                    $arr[$k]['goods_id'] = $v['id'];
                    $arr[$k]['stock'] = $instock - $outstock;
                    $arr[$k]['sn'] = $v['sn'];
                    $arr[$k]['mark'] = $v['mark'];
                    $arr[$k]['model'] = $v['model'];
                    $arr[$k]['goods_category_name'] = Db::name('goods_category')->where('id', $v['goods_category_id'])->value('name');
                    $arr[$k]['unit_id'] = $v['unit'];
                    $arr[$k]['unit_name'] = Db::name('unit')->where('id', $v['unit'])->value('name');
                }
            }
            // halt($arr);
            return $this->grid_data($arr, $count, $page, $limit);
        }

        return $this->fetch();
    }

    public function save()
    {
        $data = $this->request->param();

        $details = $data['movedata'];
        unset($data['movedata']);

        if (empty($data['id'])) {
            $check = [
                'addtime' => time(),
                'by' => $this->Userinfo['id'],
                'sn' => osn('PD', 2),
                'store_id' => $data['store_id'],
                'enterprise_id' => $this->EnterpriseId
            ];

            $model = new Model();
            Db::startTrans();
            $result = $model->allowField(true)->save($check);

            if (!$result) {
                Db::rollback();
                return json(['status' => 0, 'msg' => '操作失败']);
            }

            foreach ($details as $key => $value) {
                $details[$key]['pid'] = $model->id;
                $details[$key]['enterprise_id'] = $this->EnterpriseId;
            }

            $checkDetails = new ModelDetails();
            $res = $checkDetails->allowField(true)->saveAll($details);
            if (!$res) {
                Db::rollback();
                return json(['status' => 0, 'msg' => '操作失败']);
            }

            Db::commit();
        } else {
            foreach ($details as $key => $value) {
                $details[$key]['pid'] = $data['id'];
                $details[$key]['enterprise_id'] = $this->EnterpriseId;
            }
            $checkDetails = new ModelDetails();
            $res = $checkDetails->allowField(true)->saveAll($details);
            if (!$res)
                return json(['status' => 0, 'msg' => '操作失败']);
        }
        if (isset($data['pandian']) && !empty($data['pandian'] == 1)) {
            $order = self::check($details);
            return json(['status' => 2, 'msg' => '保存成功', 'pid' => $details[0]['pid'],  'rk' => !empty($order['rk']) ? 1 : 0, 'ck' => !empty($order['ck']) ? 1 : 0]);
        } else {
            return json(['status' => 1, 'msg' => '保存成功']);
        }
    }

    public function edit($id)
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $list = Db::name('check_details')->where('pid', $id)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($list as $key => $value) {
                $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
                $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
                $list[$key]['goods_category_name'] = Db::name('goods_category')->where('id', $goods['goods_category_id'])->value('name');
                $list[$key]['goods_sn'] = $goods['sn'];
                $list[$key]['goods_name'] = $goods['name'];
                $list[$key]['goods_mark'] = $goods['mark'];
                $list[$key]['goods_model'] = $goods['model'];
                $list[$key]['unit_name'] = Db::name('unit')->where('id', $goods['unit'])->value('name');
            }

            return $this->grid_data($list, count($list), $page, $limit);
        }

        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * @desc 获取盘盈盘亏数据
     * @param $details 表格数据
     * @return 盈亏数据
     */
    public function check($details)
    {
        $rk = [];
        $ck = [];
        foreach ($details as $key => $value) {
            $temp = $value['difference'] <=> 0;
            switch ($temp) {
                case 1:
                    array_push($rk, $details[$key]);
                    break;
                case -1:
                    array_push($ck, $details[$key]);
                    break;
                default:
                    # code...
                    break;
            }
        }

        if (!empty($rk))
            foreach ($rk as $k => $v)
                $rk[$k]['number'] = intval($v['difference']);

        if (!empty($ck))
            foreach ($ck as $k => $v)
                $ck[$k]['number'] = intval(abs($v['difference']));

        return ['rk' => $rk, 'ck' => $ck];
    }
}
